#include "mainwindow.h"
#include "ui_drawing.h"
#include "drawing.h"
#include <QHBoxLayout>
#include <QPushButton>
#include <QDesignerLoader>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    // 创建绘图场景
    DrawingScene *scene = new DrawingScene(this);
    scene->setSceneRect(0, 0, 2000, 2000);

    // 创建绘图视图
    QGraphicsView *view = new QGraphicsView(scene, this);
    view->setRenderHint(QPainter::Antialiasing);
    view->setWindowTitle("Drawing Tool");

    // 加载UI文件
    QDesignerLoader loader;
    QFile file(":/drawing.ui");
    file.open(QIODevice::ReadOnly);
    loader.addPluginPath(QLibraryInfo::location(QLibraryInfo::PluginsPath));
    QWidget *widget = loader.load(&file, this);
    file.close();

    // 获取UI文件中的布局和按钮控件
    QHBoxLayout *layout = widget->findChild<QHBoxLayout*>("horizontalLayout");
    QPushButton *undoButton = widget->findChild<QPushButton*>("undoButton");
    QPushButton *redoButton = widget->findChild<QPushButton*>("redoButton");

    // 将按钮添加到水平布局中
    layout->addWidget(undoButton);
    layout->addWidget(redoButton);

    // 将撤销和前进按钮禁用
    undoButton->setEnabled(false);
    redoButton->setEnabled(false);

    // 连接撤销和前进按钮的槽函数
    connect(undoButton, &QPushButton::clicked, scene, &DrawingScene::undo);
    connect(redoButton, &QPushButton::clicked, scene, &DrawingScene::redo);

    // 连接绘图场景的信号和槽函数
    connect(scene, &DrawingScene::changed, [undoButton, redoButton, scene]() {
        undoButton->setEnabled(scene->canUndo());
        redoButton->setEnabled(scene->canRedo());
    });

    // 设置主窗口的中心部件为绘图视图
    setCentralWidget(view);
    setCentralWidget(widget);
}

MainWindow::~MainWindow()
{
    delete ui;
}
